package javaBase.ArraySort;

import static java.util.Collections.binarySearch;

/**
 * @program: jvm
 * @description
 * @author: tkk fendoukaoziji
 * @create: 2019-05-08 09:22
 **/
public class BinarySearch {
    public static void main(String[] args) {
        int[] array= new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9,10};
        boolean flag = binarySearchMy(array, 7);
        int i = binarySearchInt(array, 11);
        System.out.println(i);
        System.out.println(flag);
    }

    private static int binarySearchInt(int[] a, int key) {
        int size=a.length-1;
        int low=0;
        int high=size;
        int mid;
        while (true){
            mid=(high+low)/2;
            if(a[mid]==key){
                return 1;
            }else if(low>high){
                return -1;
            }else {
                if(a[mid]>key){
                    high=mid-1;
                }else{
                    low=mid+1;
                }
            }
        }
    }

    private static boolean binarySearchMy(int[] a, int key) {
        int size=a.length-1;
        int low=0;
        int high=size;
        int mid;
        while(low<high){
            mid=(high+low)/2;
            if(low>mid){
                return false;
            }
            if(a[mid]==key){
                return true;
            }else if(a[mid]>key){
                high=mid-1;
            }else{
                low=mid+1;
            }
        }
        return false;
    }


}
